package com.gyj.config;

import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.aop.interceptor.PerformanceMonitorInterceptor;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.gyj.util.DynamicRoutingDataSource;

@Configuration
public class MybatisPlusConfig {
	@Resource
	private Map<Object, Object> dataSourceMap;

	@Resource
	private DataSourceBuilder dataSourceBuilder;

	@Resource
	private TenantDatasouceConfig tdc;

	@Bean
	public PaginationInnerInterceptor paginationInnerInterceptor() {
		return new PaginationInnerInterceptor();
	}

	@Bean
	public PerformanceMonitorInterceptor performanceMonitorInterceptor() {
		return new PerformanceMonitorInterceptor();
	}

	/**
	 * Dynamic data source.
	 *
	 * @return the data source
	 */
	@Bean("dynamicDataSource")
	public DataSource dynamicDataSource() {
		DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();

		dataSourceBuilder.url(String.format(
				"jdbc:mysql://%s:%d?useSSL=false&useUnicode=true&characterEncoding=utf8&autoReconnect=true",
				tdc.getHost(), tdc.getPort()));
		dataSourceBuilder.username(tdc.getUsername());
		dataSourceBuilder.password(tdc.getPassword());
		DataSource dataSource = dataSourceBuilder.build();

		dataSourceMap.put(0L, dataSource);
		dynamicRoutingDataSource.setDefaultTargetDataSource(dataSource);
		// 可动态路由的数据源里装载了所有可以被路由的数据源
		dynamicRoutingDataSource.setTargetDataSources(dataSourceMap);

		return dynamicRoutingDataSource;
	}

}
